 //
//  ChangeShiftViewController.m
//  DigiOps
//
//  Created by app on 2018/8/1.
//  Copyright © 2018年 俞渊华. All rights reserved.
//

#import "ChangeShiftViewController.h"
#import "SopViewCell.h"
#import "SopOptionViewCell.h"
#import "DetailViewController.h"
#import "SopOptionViewController.h"
#import "SopTextViewCell.h"
#import "SopPhotoViewCell.h"
#import "SopAddPicViewController.h"
#import "ChangeShiftViewCell.h"
#import "WBPopMenuModel.h"
#import "WBPopMenuSingleton.h"
#import "WBPopMenuView.h"
#import "SopViewCell.h"
#import "SopTextViewController.h"
#import "SopNotokViewController.h"
#import "XTAlertViewController.h"
#import "UserSites.h"
#import "ShiftModel.h"
#import "contentListShift.h"
#import "PointModel.h"
#import "PointModelOffline.h"
#import "PointValueModel.h"
#import "HomeViewController.h"
#import "pictureData.h"

@interface ChangeShiftViewController ()<XTAlertControllerDelegate>
@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)NSMutableArray *sopArray;

@property(nonatomic, assign)NSInteger pageSize;
@property(nonatomic, assign)NSInteger pageIndex;
@property(nonatomic, strong)UILabel* titleLabelb;
@property(nonatomic, strong)NSString* seq;
@property(nonatomic, assign)int rejectCount;
@property(nonatomic, strong)NSString* shiftUuid;
@property(nonatomic,assign)NSString* refuseRemark;
@property(nonatomic,assign)BOOL okSubmit;

@end

@implementation ChangeShiftViewController

static ChangeShiftViewController *csv = nil;

+ (instancetype)share {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        csv = [[self alloc] init];
    });
    return csv;
}
//加了保安队长看详情的逻辑，可能提交或者OK，NOTOK部分有问题
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _rejectCount=0;
    CGRect labelFrame = CGRectMake(0.0, 0.0, SCREEN_WIDTH, 36.0);
    UILabel *label = [[UILabel alloc] initWithFrame:labelFrame];
    label.font = [UIFont boldSystemFontOfSize:18];
    label.numberOfLines = 2;
    label.backgroundColor = [UIColor clearColor];
    label.textAlignment = UITextAlignmentLeft;
    label.textColor = [UIColor whiteColor];
    //    label.shadowColor = [UIColor blackColor];
    //    label.shadowOffset = CGSizeMake(0.0, -1.0);
    label.lineBreakMode = UILineBreakModeMiddleTruncation;
    label.text=@"交班";
    self.navigationItem.titleView = label;
    
//    UIBarButtonItem *myButton = [[UIBarButtonItem alloc] initWithTitle:@"提交" style:UIBarButtonItemStyleBordered target:self action:@selector(clickEvent)];
//    [myButton setTintColor:[UIColor whiteColor]];
    
    //提交按钮
    UIView *rightButtonView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 150, 50)];

    UIButton *mainAndSearchBtn = [[UIButton alloc] initWithFrame:CGRectMake(100, 0, 50, 50)];
    
    [rightButtonView addSubview:mainAndSearchBtn];
    
    [mainAndSearchBtn setImage:[UIImage imageNamed:@"overflow_icon"] forState:UIControlStateNormal];
    
    [mainAndSearchBtn addTarget:self action:@selector(clickEvent) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightCunstomButtonView = [[UIBarButtonItem alloc] initWithCustomView:rightButtonView];
    if (![MySingleton sharedMySingleton].finished) {
        if (_model.executeState!=1)
            self.navigationItem.rightBarButtonItem = rightCunstomButtonView;
    }

    self.pageSize = 20;
    self.pageIndex = 1;
    self.sopArray = [NSMutableArray array];
    [self.view addSubview:self.tableView];
    
    /** MJRefresh的block也需要用若引用 */
    WEAKSELF
//    self.tableView.mj_header = [XMRefreshHeader xm_headerWithRefreshingBlock:^{
//        self.pageIndex = 1;
////        [self.sopArray removeAllObjects];
//        //        [weakSelf searchAticle];
//    }];
    //默认block方法：设置上拉加载更多
    //保安队长要收交接班
    if (![[UserInfo share].role.powerType isEqualToString:@"1"]&&_model.executeState!=[@"0" integerValue]) {
        if (![MySingleton sharedMySingleton].network) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"友情提醒" message:@"请检查网络状态" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
            return;
        }
        [self postFinishUI];
    }
    //调本地存储
    NSArray * array = [PointModel findWhere:@[@"uuid",@"=",_model.uuid]];
    if (array.count>0) {
         [self.sopArray removeAllObjects];
        [self.sopArray addObjectsFromArray:array];
        
        //排序
        NSArray *sortArray = [self.sopArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
            
            PointModel *pModel1 = obj1;
            PointModel *pModel2 = obj2;
            if ([pModel1.seq intValue] > [pModel2.seq intValue]) { //不使用intValue比较无效
                return NSOrderedDescending;//降序
            }else if ([pModel1.seq intValue] < [pModel2.seq intValue]){
                return NSOrderedAscending;//升序
            }else {
                return NSOrderedSame;//相等
            }
            
        }];
        [self.sopArray removeAllObjects];
        self.sopArray=[NSMutableArray arrayWithArray:sortArray];
        //赋值sopuuid
        for (PointModel* pm in array) {
            _shiftUuid=pm.shiftUuid;
            self.titleLabelb.text=pm.offlineName;
            break;
        }
        
        [self.tableView reloadData];
    }
    else
    {
        if ([MySingleton sharedMySingleton].finished&&![[UserInfo share].role.powerType isEqualToString:@"1"]) {
            [self postFinishUI];
        }
        else{
        //离线存储
        NSArray * array1 = [PointModelOffline findWhere:@[@"offlineuuid",@"=",_model.orderTypeUuid]];
        NSMutableArray* Temp1=[NSMutableArray new];
        for (PointModelOffline* model in array1) {
            if ([model.pointNum isEqualToString:_model.orderTypeUuid]) {
                PointModel* aa=[PointModel new];
                aa.seq=model.seq;
                aa.title=model.title;
                aa.content=model.content;
                aa.shiftUuid=model.shiftUuid;
                aa.sopUuid=model.sopUuid;
                aa.auditUuid=model.auditUuid;
                aa.categoryName=model.categoryName;
                aa.categoryWeight=model.categoryWeight;
                aa.type=model.type;
                aa.valueArr=model.valueArr;
                aa.picture=model.picture;
                aa.remark=model.remark;
                aa.uuid=_model.uuid;//工单的uuid
                aa.pointNum=model.pointNum;
                aa.offlineName=model.offlineName;
                
                [Temp1 addObject:aa];
            }
            
        }
        if (Temp1.count>0) {
            [self.sopArray removeAllObjects];
            [self.sopArray addObjectsFromArray:Temp1];
            
            //排序
            NSArray *sortArray = [self.sopArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
                
                PointModel *pModel1 = obj1;
                PointModel *pModel2 = obj2;
                if ([pModel1.seq intValue] > [pModel2.seq intValue]) { //不使用intValue比较无效
                    return NSOrderedDescending;//降序
                }else if ([pModel1.seq intValue] < [pModel2.seq intValue]){
                    return NSOrderedAscending;//升序
                }else {
                    return NSOrderedSame;//相等
                }
                
            }];
            [self.sopArray removeAllObjects];
            self.sopArray=[NSMutableArray arrayWithArray:sortArray];
            //赋值sopuuid
            for (PointModel* pm in Temp1) {
                _shiftUuid=pm.shiftUuid;
                self.titleLabelb.text=pm.offlineName;
                break;
            }
            
            [self.tableView reloadData];
        }
        else{
        //保安队长要收交接班
    if ([MySingleton sharedMySingleton].finished||![[UserInfo share].role.powerType isEqualToString:@"1"]) {
        
        [self postFinishUI];
    }
    else
    {
            [self postUI];
    }
        }
        }
    }
    
    //返回
    self.navigationItem.hidesBackButton = YES;
    UIImage *image = [UIImage imageNamed:@"Back"];
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(0, 0, 30, 44);
    backButton.imageEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
    [backButton setImage:image forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftItemsSupplementBackButton = YES;
}
-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
}

-(void)goBack
{
    //去除乱码
//    for (PointModel* pm in self.sopArray) {
//        if ([pm.content hasPrefix:@"[{"]) {
//            if (pm.valueArr.count>0) {
//                PointValueModel* a=pm.valueArr[0];
//                pm.content=a.value;
//            }
//        }
//        if ([pm.content isEqualToString:@"[]"]) {
//            pm.content=@"";
//        }
//    }
//    if (_model.executeState==1)
//        [self submitSOP];
//    else
//    {
        NSArray * array = [PointModel findWhere:@[@"uuid",@"=",_model.uuid]];
        if (array.count>0) {
            //删除sopuuid的pointmodel
            for (PointModel* pm in array) {
                [PointModel deleteWhere:@[@"shiftUuid",@"=",_shiftUuid]];
            }
        }
        for (PointModel* pm in self.sopArray) {
            [pm saveOrUpdateAsync:^(BOOL isSuccess) {
                
            }];
        }
        _model.lines=self.sopArray;

        [self.rt_navigationController popViewControllerAnimated:YES];
//    }
}
-(void)searchAticle{
    
}
-(void)postUI{
    UserSites* s=[UserSites mj_objectWithKeyValues:[UserInfo share].sites[0]];
    
    NSDictionary *params = @{
                             @"siteUuid" : s.uuid
                             };
    [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    [HttpTool get:[NSString stringWithFormat:@"digiops/app/SelectShifts"] params:nil success:^(id responseObj) {
        NSLog(@"");
        [self.sopArray removeAllObjects];
        for (NSDictionary* shift in responseObj[@"content"]) {
            ShiftModel* a=[ShiftModel mj_objectWithKeyValues:shift];
            //
            if ([_model.orderTypeUuid isEqualToString:a.uuid]) {

            self.titleLabelb.text=a.shiftName;
            for (NSDictionary* template in a.shiftTemplates) {
                PointModel* p=[PointModel mj_objectWithKeyValues:template];
                
                NSData *data = [p.content dataUsingEncoding:NSUTF8StringEncoding];
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                NSMutableArray* arr=[NSMutableArray new];
                for (NSDictionary* v in dict) {
                    PointValueModel* model=[PointValueModel mj_objectWithKeyValues:v];
                    [arr addObject:model];

                }
                p.valueArr=arr;
                NSLog(@"");
                p.shiftUuid=a.uuid;
                _shiftUuid=s.uuid;
                p.uuid=_model.uuid;
                [self.sopArray addObject:p];
                
            }
            NSLog(@"");
            }
        }
        //离线存储
        for (NSDictionary* shift in responseObj[@"content"]) {
            ShiftModel* a=[ShiftModel mj_objectWithKeyValues:shift];

            for (NSDictionary* template in a.shiftTemplates) {

                PointModelOffline* p=[PointModelOffline mj_objectWithKeyValues:template];
                
                NSData *data = [p.content dataUsingEncoding:NSUTF8StringEncoding];
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                NSMutableArray* arr=[NSMutableArray new];
                for (NSDictionary* v in dict) {
                    PointValueModel* model=[PointValueModel mj_objectWithKeyValues:v];
                    [arr addObject:model];
                    
                }
                p.valueArr=arr;
                NSLog(@"");
                p.shiftUuid=a.uuid;
                p.uuid=_model.uuid;

                p.offlineuuid=a.uuid;
                p.pointNum=a.uuid;
                [p saveOrUpdateAsync:^(BOOL isSuccess) {
                    
                }];
                NSLog(@"");
            }
            NSLog(@"");
            
        }
        //排序
        NSArray *sortArray = [self.sopArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
            
            PointModel *pModel1 = obj1;
            PointModel *pModel2 = obj2;
            if (pModel1.seq > pModel2.seq) { //不使用intValue比较无效
                return NSOrderedDescending;//降序
            }else if (pModel1.seq < pModel2.seq){
                return NSOrderedAscending;//升序
            }else {
                return NSOrderedSame;//相等
            }
            
        }];
        [self.sopArray removeAllObjects];
        self.sopArray=[NSMutableArray arrayWithArray:sortArray];
        
        [self.tableView reloadData];
        NSLog(@"");
        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
    } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        //        [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"登录失败，稍后再试" withTime:1.0];
        
        //        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        
    }];
}
-(void)postFinishUI{
    UserSites* s=[UserSites mj_objectWithKeyValues:[UserInfo share].sites[0]];
    
    NSDictionary *params = @{
                             @"uuid" : _model.uuid,
                             @"workOrderType" : @(_model.workOrderType)
                             };
    [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    [HttpTool post:[NSString stringWithFormat:@"digiops/app/workOrder/SelectFindById"] params:params success:^(id responseObj) {
        NSLog(@"");
        [self.sopArray removeAllObjects];
        for (NSDictionary* shift in responseObj[@"content"]) {
            PointModel* a=[PointModel mj_objectWithKeyValues:shift];
            //
  
                
//                self.titleLabelb.text=a.shiftName;
            
//                    PointModel* p=[PointModel mj_objectWithKeyValues:template];
//
//                    NSData *data = [p.content dataUsingEncoding:NSUTF8StringEncoding];
//                    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
//                    NSMutableArray* arr=[NSMutableArray new];
//                    for (NSDictionary* v in dict) {
//                        PointValueModel* model=[PointValueModel mj_objectWithKeyValues:v];
//                        [arr addObject:model];
//
//                    }
//                    p.valueArr=arr;
            a.shiftUuid=a.templateUuid;//templateuuid取不到
                    NSLog(@"");
                    [self.sopArray addObject:a];
                    

        }
        [self.tableView reloadData];
        NSLog(@"");
        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
    } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        //        [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"登录失败，稍后再试" withTime:1.0];
        
        //        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        
    }];
}

//gcd
-(void)gcdpost
{
    NSMutableArray* t=[NSMutableArray new];
    for (WorkOrderModel* m in self.orderCopy) {
        if (m.executeState==1&&m.workOrderType==1) {
            [t addObject:m];
        }
        if (m.executeState==2&&m.workOrderType==1) {
            [t addObject:m];
        }
    }
//    for (WorkOrderModel* m in self.orderCopy) {
//        if (m.executeState==3&&m.workOrderType==1) {
//            [t addObject:m];
//        }
//    }
    [MySingleton sharedMySingleton].totalCount=[MySingleton sharedMySingleton].totalCount+t.count;
    if (t.count==0) {
        return;
    }
    //    [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    
    WorkOrderModel* m=(WorkOrderModel*)t[0];
    NSBlockOperation* op=[NSBlockOperation blockOperationWithBlock:^{
        [self postSubmitUI:m];
    }];
    for (int i=1; i<t.count; i++) {
        [op addExecutionBlock:^{
            [self postSubmitUI:(WorkOrderModel*)t[i]];
        }];
    }
    [op start];
}
-(void)postSubmitUI:(WorkOrderModel*)m
{
    if (m.executeState==2) {
        [self postSubmitUIreject:m];
        return;
    }
    //时间问题
    NSDateFormatter *isoFormat = [[NSDateFormatter alloc] init];
    [isoFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS"];
    
    
    NSDate*nowDate = [NSDate date];
    NSDate* theDate;
    
    
    theDate = nowDate;
    NSString* workStart=[self eightHour:theDate];
    m.workEndDate=workStart;
    if (!m.workStartDate) {
        m.workStartDate=workStart;
        //        dispatch_async(dispatch_get_main_queue(), ^{
        //            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"消息" message:@"请到任务详情重新提交" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        //            [alert show];
        //
        //        });
        //        return;
    }
    //
    //    UserSites* s=[UserSites mj_objectWithKeyValues:[UserInfo share].sites[0]];
    NSMutableArray* content=[NSMutableArray new];
    for (PointModel* model in m.lines) {
        //去除乱码
        if ([model.content hasPrefix:@"[{"]) {
            if (model.valueArr.count>0) {
                PointValueModel* a=model.valueArr[0];
                model.content=a.value;
            }
        }
        if ([model.content isEqualToString:@"[]"]) {
            model.content=@"";
        }

    contentListShift* cl=[[contentListShift alloc] init];
    cl.templateUuid=model.shiftUuid;
    cl.title=model.title;
    cl.type=model.type;
        cl.content=model.content;
        if ([model.content isEqualToString:@""]) {
            cl.content=@"正常";
        }
        if ([self getDuplicateSubStrCountInCompleteStr:cl.content withSubStr:@"-"]>2) {
            NSArray* pic=[pictureData findWhere:@[@"picuuid",@"=",cl.content]];
            if (pic.count>0) {
                pictureData* pd=[pic objectAtIndex:0];
                if (pd.picurl) {
                    cl.content=pd.picurl;
                }
                NSMutableString* uu=[NSMutableString new];
                if (pd.multi.count>1) {
                    for (int i=0; i<pd.multi.count; i++) {
                        NSArray* pics=[pictureData findWhere:@[@"picuuid",@"=",[pd.multi objectForKey:[NSString stringWithFormat:@"%i",i]]]];
                        if (pics.count>0) {
                            pictureData* pds=[pics objectAtIndex:0];
                            
                            [uu appendString:pds.picurl];
                            if (i!=pd.multi.count)
                                [uu appendString:@","];
                        }
                        
                    }
                    if ([uu hasSuffix:@","]) {
                        uu=[self removeLastOneChar:uu];
                    }
                    cl.content=uu;
                }
            }
        }
        if ([model.type isEqualToString:@"picture"]) {
            if ([cl.content isEqualToString:@"正常"]) {
                cl.content=@"";
            }
        }
//        if ([model.type isEqualToString:@"button"]) {
//            cl.content=@"[{\"value\":\"dd\"}]";
//
//        }
    cl.remark=model.remark;
    cl.picture=model.picture;
        if ([self getDuplicateSubStrCountInCompleteStr:cl.picture withSubStr:@"-"]>2) {
            NSArray* pic=[pictureData findWhere:@[@"picuuid",@"=",cl.picture]];
            if (pic.count>0) {
                pictureData* pd=[pic objectAtIndex:0];
                if (pd.picurl) {
                    cl.picture=pd.picurl;
                }
                NSMutableString* uu=[NSMutableString new];
                if (pd.multi.count>1) {
                    for (int i=0; i<pd.multi.count; i++) {
                        NSArray* pics=[pictureData findWhere:@[@"picuuid",@"=",[pd.multi objectForKey:[NSString stringWithFormat:@"%i",i]]]];
                        if (pics.count>0) {
                            pictureData* pds=[pics objectAtIndex:0];
                            
                            [uu appendString:pds.picurl];
                            if (i!=pd.multi.count)
                                [uu appendString:@","];
                        }
                        
                    }
                    if ([uu hasSuffix:@","]) {
                        uu=[self removeLastOneChar:uu];
                    }
                    cl.picture=uu;
                }
                
            }
        }
    cl.seq=model.seq;
    [content addObject:cl];
    }
    NSArray *dictArray = [contentListShift mj_keyValuesArrayWithObjectArray:content];
    if (!m.workOrderRemark)
        m.workOrderRemark=@"交班";
    NSDictionary *params = @{
                             @"orderUuid" : m.uuid,
                             @"workOrderType" : @(m.workOrderType),
                             @"workOrderRemark" : m.workOrderRemark,
                             @"executeState" : @1,
                             @"workStartDate" : m.workStartDate,
                             @"workEndDate" : m.workEndDate,
                             @"contentList" : dictArray.mj_JSONString
                             
                             };
    NSLog(@"");
    MJExtensionLog(@"%@", params);
    MJExtensionLog(@"%@", dictArray.mj_JSONString);
    dispatch_async(dispatch_get_main_queue(), ^{
        [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    });
    [HttpTool post:@"digiops/app/workOrder/InsertWorkOrderData" params:params success:^(id responseObj) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        });
        [WorkOrderModel deleteWhere:@[@"uuid",@"=",m.uuid] ];
        [MySingleton sharedMySingleton].succCount++;

//        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
//        [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"提交成功" withTime:1.0];
        
    } failure:^(NSError *error) {
        [MySingleton sharedMySingleton].nosuccCount++;

        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        });
//        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        //        [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"登录失败，稍后再试" withTime:1.0];
        
        //        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        NSLog(@"");

    }];
}

-(void)clickEvent{
    if (_model.executeState==1) {
        return;
    }
    NSMutableArray *obj = [NSMutableArray array];
    
    for (NSInteger i = 0; i < [self titles].count; i++) {
        
        WBPopMenuModel * info = [WBPopMenuModel new];
//        info.image = [self images][i];
        info.title = [self titles][i];
        [obj addObject:info];
    }
    
    [[WBPopMenuSingleton shareManager]showPopMenuSelecteWithFrame:150
                                                             item:obj
                                                           action:^(NSInteger index) {
                                                               NSLog(@"index:%ld",(long)index);
                                                               if ([[UserInfo share].role.powerType isEqualToString:@"1"]) {

                                                               if (index==0) {
                                                                   _okSubmit=NO;
                                                                   [self rejectSOP];
                                                               }
                                                               else
                                                               {
                                                                   [MySingleton sharedMySingleton].reject=NO;
                                                                   _okSubmit=YES;
                                                                   [self submitSOP];
                                                               }
                                                               }
                                                               else
                                                               {
                                                                   _okSubmit=YES;
                                                                   [self submitSOP];
                                                               }
                                                           }];
}
- (NSArray *) titles {
    if ([[UserInfo share].role.powerType isEqualToString:@"1"]) {
        return @[@"拒绝",@"提交"];
    }
    else
    {
    return @[@"提交"];
    }
}

- (NSArray *) images {
    return @[@"right_menu_QR@3x",
             @"right_menu_addFri@3x",
             @"right_menu_multichat@3x",
             @"right_menu_sendFile@3x",
             @"right_menu_facetoface@3x",
             @"right_menu_payMoney@3x"];
}

-(void)submitSOP
{
    XTAlertViewController *xtAlert = [[XTAlertViewController alloc] init];
    [xtAlert showViewWithImage:nil imageHeight:0 title:@"确认提交工单" btnTitles:@[@"取消", @"确定"] des:@"确认提交工单" style:AlertDefault fromVC:self];
    xtAlert.delegate=self;
    
}
-(void)submitSopAlert
{
//    if (_model.executeState==1||_model.executeState==2) {
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"不能提交" message:@"已提交的工单不能再次提交" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
//        [alert show];
//        return;
//    }
    NSArray * array = [PointModel findWhere:@[@"uuid",@"=",_model.uuid]];
    if (array.count>0) {
        //删除sopuuid的pointmodel
        for (PointModel* pm in array) {
            [PointModel deleteWhere:@[@"uuid",@"=",_model.uuid,@"shiftUuid",@"=",_shiftUuid]];
        }
    }
    for (PointModel* pm in self.sopArray) {
        [pm saveOrUpdateAsync:^(BOOL isSuccess) {
            
        }];
    }
    _model.lines=self.sopArray;
    if (self.block) {
        self.block(_model.uuid, self.sopArray);
    };
    [self.rt_navigationController popViewControllerAnimated:YES];
//    [self postSubmitUI];
}
-(void)rejectSOP
{
    XTAlertViewController *xtAlert = [[XTAlertViewController alloc] init];
    [xtAlert showViewWithImage:nil imageHeight:0 title:@"拒绝工单" btnTitles:@[@"取消", @"确定"] des:@"确认拒绝工单" style:AlertDefault fromVC:self];
    xtAlert.delegate=self;
}
#pragma mark -
- (void)xt_alertViewControllerClickIndex:(NSInteger)buttonIndex remark:(NSString *)rem
{
    self.refuseRemark=rem;
    if (_okSubmit) {
        switch (buttonIndex) {
            case 0:
                NSLog(@"0");
                NSLog(@"Cancel");
                break;
            case 1:
                NSLog(@"1");
                NSLog(@"Determine");
                [self submitSopAlert];
                break;
            case 2:
                NSLog(@"2");
                NSLog(@"summerxx");
                break;
            default:
                break;
        }
    }
    else
    {
    switch (buttonIndex) {
        case 0:
            NSLog(@"0");
            NSLog(@"Cancel");
            break;
        case 1:
            NSLog(@"1");
            NSLog(@"Determine");
            [MySingleton sharedMySingleton].reject=YES;
            [self postSubmitUIrejectEvent];
            break;
        case 2:
            NSLog(@"2");
            NSLog(@"summerxx");
            break;
        default:
            break;
    }
    }
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    //    return self.routeArray.count;
    return self.sopArray.count;
//    return 5;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    PointModel* model=[self.sopArray objectAtIndex:indexPath.row];
    if ([model.type isEqualToString:@"select"]) {
        SopOptionViewCell* cell=[SopOptionViewCell cellWithTableView:tableView];
        cell.pointTitle.text=[NSString stringWithFormat:@"%@.%@",model.seq, model.title];
        //自动折行设置
        cell.pointTitle.lineBreakMode = UILineBreakModeWordWrap;
        cell.pointTitle.numberOfLines = 0;
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        if ([MySingleton sharedMySingleton].finished||![[UserInfo share].role.powerType isEqualToString:@"1"])
            [cell.okButton setTitle:model.content forState:UIControlStateNormal];
        if ([model.content hasPrefix:@"["])
        {
            NSMutableArray* value=[NSMutableArray new];
            for (PointValueModel* p in model.valueArr) {
                [value addObject:p.value];
            }
            if (value.count>0)
                [cell.okButton setTitle:value[0] forState:UIControlStateNormal];
        }
        else
            [cell.okButton setTitle:model.content forState:UIControlStateNormal];
        cell.block =^(UIButton* sender){
            if ([MySingleton sharedMySingleton].finished)
                return;
            self.seq=model.seq;
            
            SopOptionViewController* detailVC = [[SopOptionViewController alloc]init];
            detailVC.model = model;
            detailVC.block = ^(NSString *txt) {
                [cell.okButton setTitle:txt forState:UIControlStateNormal];
                NSMutableArray* sopTemp=[NSMutableArray new];
                for (PointModel* model in self.sopArray) {
                    if ([model.seq isEqualToString:self.seq]) {
                        model.content=txt;
                    }
                    [sopTemp addObject:model];
                }
                [self.sopArray removeAllObjects];
                self.sopArray=sopTemp;
            };
            [self.rt_navigationController pushViewController:detailVC animated:YES];
        };
        return cell;
    }
    else if([model.type isEqualToString:@"text"]){
        self.seq=model.seq;

        SopTextViewCell* cell=[SopTextViewCell cellWithTableView:tableView];
        cell.pointTitle.text=[NSString stringWithFormat:@"%@.%@",model.seq, model.title];
        //自动折行设置
        cell.pointTitle.lineBreakMode = UILineBreakModeWordWrap;
        cell.pointTitle.numberOfLines = 0;
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        if ([MySingleton sharedMySingleton].finished||![[UserInfo share].role.powerType isEqualToString:@"1"])
            cell.textField.text=model.content;
        if ([model.content isEqualToString:@"[]"]){
            cell.textField.text=@"请在此处输入";
            [cell.textField setTextColor:[UIColor lightGrayColor]];
        }
        else{
            cell.textField.text=model.content;
            [cell.textField setTextColor:[UIColor blackColor]];
        }
        cell.block =^(){
            if ([MySingleton sharedMySingleton].finished)
                return;
            self.seq=model.seq;
            
            SopTextViewController * detailVC = [[SopTextViewController alloc]init];
            //    DetailViewController * detailVC = [[DetailViewController alloc]init];
            //    detailVC.model = self.aticleArray[indexPath.row];
            detailVC.saveText=cell.textField.text;
            detailVC.block = ^(NSString *txt) {
                if (![txt isEqualToString:@""]) {

                cell.textField.text=txt;
                [cell.textField setTextColor:[UIColor blackColor]];

                NSMutableArray* sopTemp=[NSMutableArray new];
                for (PointModel* model in self.sopArray) {
                    if ([model.seq isEqualToString:self.seq]) {
                        model.content=txt;
                    }
                    [sopTemp addObject:model];
                }
                [self.sopArray removeAllObjects];
                self.sopArray=sopTemp;
                }
                else{
                    cell.textField.text=@"请在此处输入";
                    [cell.textField setTextColor:[UIColor lightGrayColor]];
                }
                //                self.commentTxt=txt;
            };
            [self.rt_navigationController pushViewController:detailVC animated:YES];
        };
        return cell;
    }
    else if ([model.type isEqualToString:@"picture"]){
        self.seq=model.seq;

        SopPhotoViewCell* cell=[SopPhotoViewCell cellWithTableView:tableView];
        cell.pointTitle.text=[NSString stringWithFormat:@"%@.%@",model.seq, model.title];
        //自动折行设置
        cell.pointTitle.lineBreakMode = UILineBreakModeWordWrap;
        cell.pointTitle.numberOfLines = 0;
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
//        if ([MySingleton sharedMySingleton].finished)
//            [cell.okButton setImage:[UIImage imageNamed:@"ic_photo_camera_withimage"] forState:UIControlStateNormal];
        //
        if (![model.content hasPrefix:@"["]&&model.content.length>2) {
            NSArray* pic=[model.content componentsSeparatedByString:@","];
            if (pic.count>0) {
                [cell.okButton setImage:[UIImage imageNamed:@"ic_photo_camera_withimage"] forState:UIControlStateNormal];
            }
        }
        cell.block = ^(UIButton *sender) {
            self.seq=model.seq;
            SopAddPicViewController* detailVC = [[SopAddPicViewController alloc]init];
            detailVC.label=@"交班";
            detailVC.workModel=self.model;
            //    detailVC.model = self.aticleArray[indexPath.row];
            [self.rt_navigationController pushViewController:detailVC animated:YES];
            if ([MySingleton sharedMySingleton].finished||![[UserInfo share].role.powerType isEqualToString:@"1"])
            {
                NSArray* pic=[model.content componentsSeparatedByString:@","];
                detailVC.scoreArray=[pic mutableCopy];
            }
            //返回需要显示图片
            if (![model.content hasPrefix:@"["]) {
                NSArray* pic=[model.content componentsSeparatedByString:@","];
                if (pic.count>0) {
                    detailVC.scoreArray=[pic mutableCopy];
                    [cell.okButton setImage:[UIImage imageNamed:@"ic_photo_camera_withimage"] forState:UIControlStateNormal];
                }
            }
            detailVC.block = ^{
                [cell.okButton setImage:[UIImage imageNamed:@"ic_photo_camera_withimage"] forState:UIControlStateNormal];
            };
            detailVC.blockPicurl = ^(NSString *picurl) {
                NSMutableArray* sopTemp=[NSMutableArray new];
                for (PointModel* model in self.sopArray) {
                    if ([model.seq isEqualToString:self.seq]) {
                        if (picurl.length>1)
                            model.content=picurl;
                        else
                            model.content=@"";
                    }
                    [sopTemp addObject:model];
                }
                [self.sopArray removeAllObjects];
                self.sopArray=sopTemp;
            };
        };
        return cell;
    }
    else
    {
        self.seq=model.seq;
        SopViewCell* cell=[SopViewCell cellWithTableView:tableView];
        cell.pointTitle.text=[NSString stringWithFormat:@"%@.%@",model.seq, model.title];
        //自动折行设置
        cell.pointTitle.lineBreakMode = UILineBreakModeWordWrap;
        cell.pointTitle.numberOfLines = 0;
        if ([MySingleton sharedMySingleton].finished||![[UserInfo share].role.powerType isEqualToString:@"1"])
        {
            if ([model.content isEqualToString:@"正常"]) {
                [cell.okButton setSelected:YES];
            }
            else
            {
                [cell.notokButton setSelected:YES];
            }
        }
        if (model.content)
        {
            if ([model.content isEqualToString:@"正常"]) {
                [cell.okButton setSelected:YES];
            }
            else
            {
                [cell.notokButton setSelected:YES];
            }
        }
        if ([model.content hasPrefix:@"["]) {
            [cell.okButton setSelected:YES];
            [cell.notokButton setSelected:NO];
        }
        cell.block = ^{
            self.seq=model.seq;

            SopNotokViewController* detailVC = [[SopNotokViewController alloc]init];
            //    detailVC.model = self.aticleArray[indexPath.row];
            detailVC.model=model;
            detailVC.workModel=self.model;
            detailVC.shift=YES;
            [self.rt_navigationController pushViewController:detailVC animated:YES];
            detailVC.block = ^(NSString *txt) {
                NSMutableArray* sopTemp=[NSMutableArray new];
                for (PointModel* model in self.sopArray) {
                    if ([model.seq isEqualToString:self.seq]) {
                        if (txt.length>0)
                        {
                        model.remark=txt;
                        model.content=@"不正常";
                        }
                    }
                    [sopTemp addObject:model];
                }
                [self.sopArray removeAllObjects];
                self.sopArray=sopTemp;
            };
            detailVC.blockPic = ^(NSString *txt) {
                NSMutableArray* sopTemp=[NSMutableArray new];
                for (PointModel* model in self.sopArray) {
                    if ([model.seq isEqualToString:self.seq]) {
                        if (txt.length>1)
                            model.picture=txt;
                        model.content=@"不正常";
                    }
                    [sopTemp addObject:model];
                }
                [self.sopArray removeAllObjects];
                self.sopArray=sopTemp;
            };
        };
        cell.blockOK = ^{
            if ([MySingleton sharedMySingleton].finished)
                return;
            self.seq=model.seq;

            NSMutableArray* sopTemp=[NSMutableArray new];
            for (PointModel* model in self.sopArray) {
                if ([model.seq isEqualToString:self.seq]) {
                    model.content=@"正常";
                }
                [sopTemp addObject:model];
            }
            [self.sopArray removeAllObjects];
            self.sopArray=sopTemp;
        };
        return cell;
    }
    //    cell.model=[RouteModel new];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    //    AticleModel * model = self.aticleArray[indexPath.row];
    //    if (model.ViewType == 1) {
    //        return [HomeBaseCell heightWithModel:model];
    //
    //    }else if (model.ViewType == 2) {
    //        return [HomeOneImageCell heightWithModel:model];
    //
    //    }else if (model.ViewType == 3){
    //        return [NewsMoreImageCell heightWithModel:model];
    //    }else if (model.ViewType == 4){
    //        return [HomeOneImageCell heightWithModel:model];
    //    }
    return 100;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    /*
     NewsDetailViewController * detailVC = [[NewsDetailViewController alloc]init];
     detailVC.model = self.aticleArray[indexPath.row];
     [self.rt_navigationController pushViewController:detailVC animated:YES];
     */
//    DetailViewController * detailVC = [[DetailViewController alloc]init];
//    //    detailVC.model = self.aticleArray[indexPath.row];
//    [self.rt_navigationController pushViewController:detailVC animated:YES];
}


- (UITableView *)tableView{
    if (!_tableView) {
        UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.tableFooterView = [UIView new];
        UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 50)];
        view.backgroundColor = XMColor(241, 245, 247);
        UILabel* titleLabel = [[UILabel alloc]init];
        titleLabel.font = [UIFont xm_medium:17.0];
        titleLabel.numberOfLines = 1;
        titleLabel.textColor = [UIColor xm_jetblackColor];
        titleLabel.text=@"交班";
        
        [view addSubview:titleLabel];
        self.titleLabelb=titleLabel;
        tableView.tableHeaderView=view;
        
        UIView * viewFoot = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 70)];
        viewFoot.backgroundColor = [UIColor whiteColor];
        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
        //        button.frame = CGRectMake(40, 100, SCREEN_WIDTH- 80, 30);
        button.backgroundColor = DGColor;
        [button setTitle:@"提交" forState:UIControlStateNormal];
        [button addTarget:self action:@selector(submitRoute) forControlEvents:UIControlEventTouchUpInside];
        [viewFoot addSubview:button];
//        tableView.tableFooterView=viewFoot;
        //        [button setImage:[UIImage imageNamed:@"image"] forState:UIControlStateNormal];
        //        [button setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
        //        [button setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
        
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(view).offset(18);
            make.left.equalTo(view.mas_left).offset(20);
        }];
        
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(viewFoot).offset(0);
            //            make.top.equalTo(view).offset(5);
            make.width.mas_equalTo(SCREEN_WIDTH-80);
            make.height.mas_equalTo(50);
            //            make.left.equalTo(view.mas_left).offset(20);
        }];
        _tableView = tableView;
    }
    return _tableView;
}
-(void)submitRoute
{
    
}
-(void)postSubmitUIrejectEvent
{
    if ([self.refuseRemark isEqualToString:@""]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"消息" message:@"请填写拒绝原因" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return;
    }
    for (PointModel* pm in self.sopArray) {
        [pm saveOrUpdateAsync:^(BOOL isSuccess) {
            
        }];
    }
    _model.lines=self.sopArray;
    if (self.block) {
        self.block(_model.uuid, self.sopArray);
    };
    [self.rt_navigationController popViewControllerAnimated:YES];
}

-(void)postSubmitUIreject:(WorkOrderModel*)m{
    //    UserSites* s=[UserSites mj_objectWithKeyValues:[UserInfo share].sites[0]];
    NSMutableArray* content=[NSMutableArray new];
    for (PointModel* model in m.lines) {
        
        contentListShift* cl=[[contentListShift alloc] init];
        cl.templateUuid=model.shiftUuid;
        cl.title=model.title;
        cl.type=model.type;
        cl.content=model.content;
        if ([model.content isEqualToString:@""]) {
            cl.content=@"正常";
        }
//        if ([model.type isEqualToString:@"button"]) {
//            cl.content=@"[{\"value\":\"dd\"}]";
//            
//        }
        cl.remark=model.remark;
        cl.picture=model.picture;
        cl.seq=model.seq;
        [content addObject:cl];
    }
    NSArray *dictArray = [contentListShift mj_keyValuesArrayWithObjectArray:content];
    if (!m.workOrderRemark)
        m.workOrderRemark=@"交班";
    if (!self.refuseRemark) {
        self.refuseRemark=@"拒绝";
    }
    NSDictionary *params = @{
                             @"orderUuid" : m.uuid,
                             @"workOrderType" : @(m.workOrderType),
                             @"workOrderRemark" : m.workOrderRemark,
                             @"executeState" : @2,
                             @"count" : @(_rejectCount),
                             @"refuseRemark" : self.refuseRemark
                             
                             };

    NSLog(@"");
    MJExtensionLog(@"%@", params);
    MJExtensionLog(@"%@", dictArray.mj_JSONString);
    dispatch_async(dispatch_get_main_queue(), ^{
        [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    });
    [HttpTool post:@"digiops/app/workOrder/InsertWorkOrderData" params:params success:^(id responseObj) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        });
        //        [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"提交成功" withTime:1.0];
        _rejectCount++;
        _model.executeState=[@"2" integerValue];

//        HomeViewController * homeVC = [[HomeViewController alloc]init];
//        RTRootNavigationController *nav = [[RTRootNavigationController alloc] initWithRootViewController:homeVC];
//        // 添加为子控制器
//        nav.title = @"任务箱";
//        [UIApplication sharedApplication].delegate.window.rootViewController=nav;
//
//        if (self.blockReject) {
//            self.blockReject();
//        }
        [WorkOrderModel deleteWhere:@[@"uuid",@"=",m.uuid] ];
        [MySingleton sharedMySingleton].succCount++;

    } failure:^(NSError *error) {
        [MySingleton sharedMySingleton].nosuccCount++;

        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        //        [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"登录失败，稍后再试" withTime:1.0];
        
        //        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.rt_navigationController popViewControllerAnimated:YES];
        });
    }];
}

@end
//-(void)postSubmitUI:(WorkOrderModel*)m
//{
//    //    UserSites* s=[UserSites mj_objectWithKeyValues:[UserInfo share].sites[0]];
//    NSMutableArray* content=[NSMutableArray new];
//    for (PointModel* model in self.sopArray) {
//
//        contentListShift* cl=[[contentListShift alloc] init];
//        cl.templateUuid=model.shiftUuid;
//        cl.title=model.title;
//        cl.type=model.type;
//        cl.content=model.content;
//
//        //        if ([model.type isEqualToString:@"button"]) {
//        //            cl.content=@"[{\"value\":\"dd\"}]";
//        //
//        //        }
//        cl.remark=model.remark;
//        cl.picture=model.picture;
//        cl.seq=model.seq;
//        [content addObject:cl];
//    }
//    NSArray *dictArray = [contentListShift mj_keyValuesArrayWithObjectArray:content];
//    if (!_model.workOrderRemark)
//        _model.workOrderRemark=@"交班";
//        NSDictionary *params = @{
//                                 @"orderUuid" : _model.uuid,
//                                 @"workOrderType" : @(_model.workOrderType),
//                                 @"workOrderRemark" : _model.workOrderRemark,
//                                 @"executeState" : @1,
//                                 @"contentList" : dictArray.mj_JSONString
//
//                                 };
//        NSLog(@"");
//        MJExtensionLog(@"%@", params);
//        MJExtensionLog(@"%@", dictArray.mj_JSONString);
//        [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
//    [HttpTool post:@"digiops/app/workOrder/uploadOrder" params:params success:^(id responseObj) {
//
//        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
//        [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"提交成功" withTime:1.0];
//
//    } failure:^(NSError *error) {
//        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
//        //        [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"登录失败，稍后再试" withTime:1.0];
//
//        //        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
//
//    }];
//}
